<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 
            输入：nums = [1,2,3], k = 3
            输出：2
        */
        var subarraySum = function(nums, k) {
            // 注意，这题是求子数组，连续非空序列才是子数组；如果是子序列，就不是连续的
            let prefix = new Array(nums.length + 1).fill(0)
            prefix[0] = 0
            for (let i = 0; i < nums.length; i++) {
                prefix[i + 1] = prefix[i] + nums[i]
            }

            let ans = 0
            // 键统计s[j]，值是 元素和等于k的个数
            const map = new Map()
            for (const curSum of prefix) {
                if (map.get(curSum - k)) {
                    // 找到s[j] - k个s[i]，也就是元素和等于k的个数
                    ans += map.get(curSum - k) 
                }
                if (map.get(curSum)) {
                    map.set(curSum, map.get(curSum) + 1)
                } else {
                    map.set(curSum, 1)
                }
            }
            return ans
        }; 
        console.log(subarraySum([1,2,3,3,2,3], 3));
    </script>
</body>

</html>